<template>
	<view id="project">
		<u--form :model="form" :rules="rules" ref="projectForm">
			<u-form-item labelWidth="70" label="项目名称" required prop="projectName" borderBottom>
				<u--input v-model="form.projectName" placeholder="输入项目名称" border="none"></u--input>
			</u-form-item>
			<u-form-item labelWidth="70" label="项目编码" prop="projectNo" borderBottom>
				<u--input v-model="form.projectNo" placeholder="输入项目编码" border="none"></u--input>
			</u-form-item>
			<u-form-item labelWidth="70" label="项目类型" required prop="projectTypeName" @click="showProjectType = true">
				<u--input v-model="form.projectTypeName" disabled disabledColor="#fff" placeholder="选择项目类型" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="所属区域" required prop="areaName" @click="onGetArea">
				<u--input v-model="form.areaName" disabled disabledColor="#fff" placeholder="选择所属区域" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="定位" required prop="locationAddr" @click="onShowMapWrap">
				<u--input v-model="form.locationAddr" disabled disabledColor="#fff" placeholder="选择定位" border="none">
				</u--input>
				<u-icon slot="right" name="map-fill"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="项目状态" required prop="projectStatusName" @click="showProjectStatus = true">
				<u--input v-model="form.projectStatusName" disabled disabledColor="#fff" placeholder="请选择项目状态"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="开工时间" required prop="beginTime" @click="showCalendar1 = true">
				<u--input v-model="form.beginTime" disabled disabledColor="#fff" placeholder="请选择开工时间"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="竣工时间" required prop="completeTime" @click="showCalendar2 = true">
				<u--input v-model="form.completeTime" disabled disabledColor="#fff" placeholder="请选择竣工时间"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="建设单位" required prop="constructorName">
				<u--input v-model="form.constructorName" placeholder="输入建设单位"></u--input>
			</u-form-item>
			<u-form-item labelWidth="70" label="负责人" required prop="constructorContacts">
				<u--input v-model="form.constructorContacts" placeholder="输入建设单位负责人"></u--input>
			</u-form-item>
			<u-form-item labelWidth="70" label="施工单位" required prop="builderName">
				<u--input v-model="form.builderName" placeholder="输入施工单位"></u--input>
			</u-form-item>
			<u-form-item labelWidth="70" label="负责人" required prop="builderContacts" borderBottom>
				<u--input v-model="form.builderContacts" placeholder="输入施工单位负责人"></u--input>
			</u-form-item>
			<u-form-item labelWidth="70" label="业务类目" prop="projectBusinessName" @click="showProjectBusiness = true">
				<u--input v-model="form.projectBusinessName" disabled disabledColor="#fff" placeholder="请选择业务类目"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="形象照">
				<u-upload :fileList="xxList" @delete="deletePic('xx')" name="file" multiple :width="40" :height="40"
					:maxCount="1" @afterRead="xxUpload"></u-upload>
			</u-form-item>
			<u-form-item labelWidth="70" label="进度照">
				<u-upload :fileList="prgList" @delete="deletePic('prg')" name="file" multiple :width="40" :height="40"
					:maxCount="5" @afterRead="prgUpload"></u-upload>
			</u-form-item>
			<u-form-item labelWidth="70" label="备注" prop="remake">
				<u-textarea v-model="form.remake" autoHeight></u-textarea>
			</u-form-item>
		</u--form>
		<view class="submit-btn">
			<u-button type="primary" :loading="submitLoading" text="提交审核" @click="onSubmit"></u-button>
		</view>
		<u-picker closeOnClickOverlay :show="showArea" :loading="cityLoading" ref="cityPicker" :columns="cityColumns"
			@confirm="onCityConfirm" @change="onChangeCity" @cancel="onCityCancel" @close="onCloseCity"
			keyName="areaName"></u-picker>
		<u-picker closeOnClickOverlay :show="showProjectType" :columns="projectTypeOpts" @cancel="onTypeCancel"
			@confirm="onTypeConfirm" @close="onCloseType" keyName="title"></u-picker>
		<u-picker closeOnClickOverlay :show="showProjectBusiness" :columns="projectBusOpts" @cancel="onPrbCancel"
			@confirm="onPrbConfirm" @close="onClosePrb" keyName="title"></u-picker>
		<u-picker closeOnClickOverlay :show="showProjectStatus" :columns="projectStatusOpts" @cancel="onStatusCancel"
			@confirm="onStatusConfirm" @close="onCloseStatus" keyName="title"></u-picker>
		<u-calendar :show="showCalendar1" @confirm="confirmCalendar1" startText="开工时间" @close="calendarClose1" @cancel="calendarClose2"></u-calendar>
		<u-calendar :show="showCalendar2" @confirm="confirmCalendar2" startText="竣工时间" @close="calendarClose2" @cancel="calendarClose2"></u-calendar>
		<u-popup :show="showMap" @close="onCloseMap" @open="onShowMap">
			<view class="map_container">
				<map class="map" id="map" :longitude="position.longitude" :latitude="position.latitude"
					:markers="markers" scale="16"></map>
			</view>
			<view class="map_text">
				<view>
					<text class="h1">{{position.name}}</text>
					<text>{{position.desc}}</text>
				</view>
				<view>
					<u-button size="small" type="primary" text="确认定位" @click="onLocation"></u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	const amapFile = require('@/utils/amap-wx.130')
	const configMap = require('@/utils/config.js')
	import config from '@/utils/defaultConfig'
	import { addProject } from '@/api/project'
	import { getAreaList } from '@/api/global'
	import apis from '@/api/apis'
	import { ACCESS_TOKEN } from '@/store/mutaction-types'
	
	export default {
		data () {
			return {
				cityLoading: false,
				submitLoading: false,
				form: {
					projectName: '',
					projectType: '',
					areaName: '',
					areaId: '',
					locationAddr: '',
					latitude: '',
					longitude: '',
					projectType: ''
				},
				rules: {
					projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
					projectTypeName: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
					projectStatusName: [{ required: true, message: '请选择项目状态', trigger: 'change' }],
					areaName: [{ required: true, message: '请选择选择所属区域', trigger: 'change' }],
					locationAddr: [{ required: true, message: '请选择项目定位', trigger: 'change' }],
					beginTime: [{ required: true, message: '请选择开工时间', trigger: 'change' }],
					completeTime: [{ required: true, message: '请选择竣工时间', trigger: 'change' }],
					constructorName: [{ required: true, message: '请填写建设单位', trigger: 'change' }],
					constructorContacts: [{ required: true, message: '请填写建设单位负责人', trigger: 'change' }],
					builderName: [{ required: true, message: '请填写施工单位', trigger: 'change' }],
					builderContacts: [{ required: true, message: '请填写施工单位负责人', trigger: 'change' }]
				},
				position: {},
				markers: [],
				projectTypeOpts: [
					config.projectType
				],
				projectBusOpts: [
					config.projectBusiness
				],
				projectStatusOpts: [
					config.projectStatus
				],
				showProjectType: false,
				showArea: false,
				cityColumns: [],
				showMap: false,
				showCalendar1: false,
				showCalendar2: false,
				showProjectStatus: false,
				showProjectBusiness: false,
				xxList: [],
				prgList: []
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.projectForm.setRules(this.rules)
		},
		methods: {
			onChangeCity(e) {
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.cityPicker
				} = e
				if (columnIndex === 0) {
					this.cityLoading = true
					uni.$u.sleep(100).then(res => {
						picker.setColumnValues(1, this.areaList[e.index].children)
						this.cityLoading = false
					})
				}
			},
			onCityConfirm (e) {
				this.form.areaName = e.value[1].areaName
				this.form.areaId = e.value[1].id
				this.showArea = false
			},
			onGetArea () {
				getAreaList().then(res => {
					this.areaList = res.data.data
					this.cityColumns[0] = this.areaList
					this.cityColumns[1] = this.areaList[0].children
				}).finally(() => {
					this.showArea = true
				})
			},
			onCityCancel() {
				this.showArea = false
			},
			onCloseCity(e) {
				this.showArea = false
			},
			onSubmit () {
				const app = this
				app.submitLoading = true
				app.$refs.projectForm.validate().then(res => {
					addProject(this.form).then(res => {
						// if (res.code === 200) {
							app.submitLoading = false
						// }
					}).catch(error => {
						uni.$u.toast(error)
						return false
					})
				}).catch(errors => {
					app.submitLoading = false
					return false
				})
			},
			onShowMapWrap() {
				const key = configMap.Config.key
				const myAmapFun = new amapFile.AMapWX({
					key: key
				})
				myAmapFun.getRegeo({
					iconPath: "https://bc-staticfiles.oss-cn-zhangjiakou.aliyuncs.com/wechat/marker.png",
					iconWidth: 22,
					iconHeight: 32,
					success: res => {
						console.log(res)
						this.position.latitude = res[0].latitude
						this.position.longitude = res[0].longitude
						this.position.name = res[0].name
						this.position.desc = res[0].desc
						this.markers = [{
							id: res[0].id,
							latitude: res[0].latitude,
							longitude: res[0].longitude,
							iconPath: res[0].iconPath,
							width: res[0].width,
							height: res[0].height
						}]
						this.showMap = true
					},
					fail: error => {
						console.log(error)
					}
				})
			},
			onShowMap () {},
			onLocation() {
				this.form.longitude = this.position.longitude
				this.form.latitude = this.position.latitude
				this.form.locationAddr = this.position.name + this.position.desc
				this.showMap = false
			},
			onTypeCancel () {
				this.showProjectType = false
			},
			onCloseType () {
				this.showProjectType = false
			},
			onTypeConfirm (e) {
				this.form.projectType = e.value[0].id
				this.form.projectTypeName = e.value[0].title
				this.showProjectType = false
			},
			onStatusCancel () {
				this.showProjectStatus = false
			},
			onCloseStatus () {
				this.showProjectStatus = false
			},
			onStatusConfirm (e) {
				this.form.projectStatus = e.value[0].id
				this.form.projectStatusName = e.value[0].title
				this.showProjectStatus = false
			},
			confirmCalendar1 (e) {
				this.showCalendar1 = false
				this.form.beginTime = e[0]
			},
			confirmCalendar2 (e) {
				this.showCalendar2 = false
				this.form.completeTime = e[0]
			},
			onPrbCancel () {
				this.showProjectBusiness = false
			},
			onClosePrb () {
				this.showProjectBusiness = false
			},
			onPrbConfirm (e) {
				this.form.projectBusiness = e.value[0].id
				this.form.projectBusinessName = e.value[0].title
				this.showProjectBusiness = false
			},
			async xxUpload (event) {
				let lists = [].concat(event.file)
				let fileListLen = this.xxList.length
				lists.map((item) => {
					this.xxList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					console.log(lists[i].url)
					let result = await this.uploadFilePromise(lists[i].url)
					let item = this.xxList[fileListLen]
					this.xxList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			async prgUpload (event) {
				let lists = [].concat(event.file)
				let fileListLen = this.prgList.length
				lists.map((item) => {
					this.prgList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					console.log(lists[i].url)
					let result = await this.uploadFilePromise(lists[i].url)
					let item = this.prgList[fileListLen]
					this.prgList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					const a = uni.uploadFile({
						url: 'http://8.142.178.141:8888' + apis.Upload,
						filePath: url,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync(ACCESS_TOKEN)
						},
						success: res => {
							console.log(res)
							setTimeout(() => {
								resolve(res.data.data)
							}, 500)
						},
						fail: error => {
							console.log(error)
						}
					})
				})
			},
			deletePic(event) {
				this[`${event}List`].splice(event.index, 1)
			}
		}
	}
</script>

<style lang="scss" scoped>
	#project {
		padding: 0 20upx 300upx;
		.submit-btn {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			z-index: 9999
		}
		.map_container {
			width: 750upx;
			height: 750upx;
		
			#map {
				width: 750upx;
				height: 750upx;
			}
		}
		
		.map_text {
			background: #fff;
			padding: 0 15px;
			display: flex;
			justify-content: space-between;
			align-items: center;
		
			text {
				margin: 5px 0;
				display: block;
				font-size: 12px;
			}
		
			.h1 {
				margin: 15px 0;
				font-size: 15px;
			}
		}
	}
</style>
